<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img class="preview" v-if="avatar" :src="avatar" alt="" />

      <img
        class="preview"
        v-else
        src="../../../assets/images/avatar.jpg"
        alt=""
      />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input
          @change="changeHandler"
          style="display: none"
          ref="inpimg"
          type="file"
          accept="image/*"
        />
        <el-button
          @click="$refs.inpimg.click()"
          type="primary"
          icon="el-icon-plus"
          >选择图片</el-button
        >
        <el-button
          type="success"
          icon="el-icon-upload"
          :disabled="!avatar"
          @click="uploadHandlr"
          >上传头像</el-button
        >
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data () {
    return {
      avatar: ''
    }
  },
  methods: {
    changeHandler (e) {
      if (e.target.files.length === 0) return
      const fr = new FileReader()
      fr.readAsDataURL(e.target.files[0])
      fr.onload = (e) => {
        // console.log(e.target.result)
        this.avatar = e.target.result
      }
    },
    async uploadHandlr () {
      // const { data: res } =
      await this.$http.patch('/my/update/avatar', {
        avatar: this.avatar
      })
      //   console.log(res)
      // if (res.code !== 0) return this.$message.error(res.message)
      // this.$message.success(res.message)
      this.$store.dispatch('getUserInfo')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
  width: 350px;
  height: 350px;
}
</style>
